import React from 'react';

var WPS_Enum = {
    msoCTPDockPositionLeft: 0,
    msoCTPDockPositionRight: 2,
    wdAuto:0,	//自动配色。默认值；通常为黑色。
    wdBlack:1,	//黑色。
    wdUnderlineNone:0 // 无下划线
}

//扩展js string endwith,startwith方法
String.prototype.endWith = function (str) {
    if (str == null || str == "" || this.length == 0 || str.length > this.length)
        return false;
    if (this.substring(this.length - str.length) == str)
        return true;
    else
        return false;
}
String.prototype.startWith = function (str) {
    if (str == null || str == "" || this.length == 0 || str.length > this.length)
        return false;
    if (this.substr(0, str.length) == str)
        return true;
    else
        return false;
}
function GetUrlPath() {
    let e = document.location.toString()
    e = decodeURI(e)
    if (-1 !== e.indexOf("/"))
        e = e.substring(0, e.lastIndexOf("/"))
        console.log('e...........',e)
    return e
}
function deepCopy(originData) {
    let result = null;

    let dataType = getType(originData);

    if(
        dataType === 'String' || 
        dataType === 'Number' || 
        dataType === 'Boolean' ||
        dataType === 'Null' ||
        dataType === 'Undefined' ||
        dataType === 'Function' ||
        dataType === 'ReactElement'
    ) { 
        result = originData
    }
    else if(dataType === 'Object') {
        result = {};
        Object.keys(originData).forEach((key) => {
            result[key] = deepCopy(originData[key]);
        });
    }
    else if(dataType === 'Array') {
        result = originData.map((item) => {
            return deepCopy(item);
        });
    }

    return result;
 }

 function getType(data) {

    if(React.isValidElement(data)) {
        return 'ReactElement';
    }
    let dataType = Object.prototype.toString.call(data);

    dataType = dataType.substring(8, dataType.length - 1);

    return dataType;
 }
 function FormData() {
    this.fake = true;
    this.boundary = "--------FormData" + ('0.'+(+new Date()+'').split('').reverse().join(''));
    this._fields = [];
}
FormData.prototype.append = function(key, value) {
    this._fields.push([key, value]);
}
FormData.prototype.toString = function() {
    var boundary = this.boundary;
    var body = "";
    this._fields.forEach(function(field) {
        body += "--" + boundary + "\r\n";
        // file upload
        if (field[1].name) {
            var file = field[1];
            body += "Content-Disposition: form-data; name=\""+ field[0] +"\"; filename=\""+ file.name +"\"\r\n";
            body += "Content-Type: "+ file.type +"\r\n\r\n";
            body += file.getAsBinary() + "\r\n";
        } else {
            body += "Content-Disposition: form-data; name=\""+ field[0] +"\";\r\n\r\n";
            body += field[1] + "\r\n";
        }
    });
    body += "--" + boundary +"--";
    return body;
}
const FakeFormData = FormData;

function _Ajax(url,data,callback){
    return new Promise((resolve, reject) => {
        let XHR = new XMLHttpRequest();
        XHR.open('POST', url)
        XHR.setRequestHeader('content-type','application/json;charset=UTF-8');
        // "pk_rpt_def":"1001Z710000000000JB4"
        // XHR.responseType = 'blob';
        XHR.onreadystatechange = handle;
        let postData = {
            "busiParamJson":JSON.stringify(data),
            "sysParamJson":{"busiaction":"wps-获取文档","appcode":data.appcode,"ts":window.cookiets || window.top.cookiets,"from":"","pagecs":window.cookiets || window.top.cookiets}
        }
       
        XHR.send(JSON.stringify(postData));
        function handle(){
            if(XHR.readyState !== 4) {
                return
            }
            if(XHR.status === 200) {
                resolve(XHR.response)
            }else{
                reject(new Error(XHR.statusText))
            }

        }
    })

}

/**
 * wps内弹出web页面
 * @param {*} html 文件名
 * @param {*} title 窗口标题
 * @param {*} hight 窗口高
 * @param {*} width 窗口宽
 */
 function OnShowDialog(html, title, height, width, bModal) {
    var l_ActiveDoc = wps.WpsApplication().ActiveDocument;
    if (!l_ActiveDoc) {
        alert("WPS当前没有可操作文档！")
        return;
    }
    if (typeof bModal == "undefined" || bModal == null) {
        bModal = true;
    }
    width *= window.devicePixelRatio;
    height *= window.devicePixelRatio;
    var url = getHtmlURL(html);
    console.log("commonJS中获取的地址",url)
    wps.ShowDialog(url, title, height, width, bModal);
}

/**
 * 获取文件路径
 * @param {*} html 文件全称
 */
 function getHtmlURL(html) {
    //弹出辅助窗格框
    var GetUrlPath = ()=> {
        var e = document.location.toString();
        return -1 != (e = decodeURI(e)).indexOf("/") && (e = e.substring(0, e.lastIndexOf("/"))), e
    }

    var url = GetUrlPath();

    if (url.length != 0) {
        url = url.concat("/" + html);
    } else {
        url = url.concat("./" + html);
    }
    return url;
}
export default {
    FakeFormData,
    deepCopy,
    WPS_Enum,
    GetUrlPath,
    _Ajax,
    OnShowDialog
}